<template>
<div id="manage">
	
	<!-- 添加或修改对话框 -->
	<el-dialog :title="operateType === 'add' ? '新增新闻' : '更新新闻'" :visible.sync="isShow" width="780px" append-to-body>
	   <el-form :model="operateForm" :rules="rules" ref="form" label-width="90px">
	      <el-row>
	         <el-col :span="24">
	            <el-form-item label="新闻分类" prop="infoKind">
<!-- 	               <el-input v-model="operateForm.infoKind" placeholder="请输入新闻分类" maxlength="30" /> -->
				   <treeselect
				     v-model="operateForm.infoKind"
				     :options="kindOptions"
				     :normalizer="normalizer"
				     :show-count="true"
				     placeholder="选择上级分类"
				   />
	            </el-form-item>
	         </el-col>
	      </el-row>		      
		  <el-row>
	         <el-col :span="24">
				 <el-form-item label="新闻标题" prop="infoTitle">
				    <el-input v-model="operateForm.infoTitle" placeholder="请输入新闻标题" maxlength="30" />
				 </el-form-item>
	         </el-col>
	      </el-row>
	      <el-row>
	         <el-col :span="24">
	            <el-form-item label="新闻内容" prop="infoContent">
				   <editor v-model="operateForm.infoContent" :min-height="192"/>
	            </el-form-item>
	         </el-col>
	      </el-row>	
	   </el-form>
	   <template #footer>
	      <div class="dialog-footer">
	         <el-button type="primary" @click="confirm">确 定</el-button>
	         <el-button @click="isShow = false">取 消</el-button>
	      </div>
	   </template>
	</el-dialog>
	
	<div class="manage-header">
		<el-form style="width: 100%;" label-width="100px" :model="queryParams" ref="sform" inline>
			<el-button type="primary" @click="addHandler">+ 新增</el-button>
			<div style="float: right;">
				<el-form-item label="关键字" prop="infoTitle">
				  <el-input
				    v-model="queryParams.infoTitle"
				    placeholder="请输入关键字"
				    clearable
				    style="width: 240px"
				    @keyup.enter.native="handleQuery"
				  />
				</el-form-item>
				<el-button  type="primary" @click="getList(queryParams.infoTitle)">搜索</el-button>
			</div>
		</el-form>
	</div>
	
	<el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="新闻编号" align="center" prop="id" min-width="20%"/>
      <el-table-column label="新闻标题" align="center" prop="infoTitle" :show-overflow-tooltip="true" min-width="20%"/>
	  <el-table-column label="新闻分类" align="center" prop="infoKindName" :show-overflow-tooltip="true" min-width="20%"/>
	  <el-table-column label="创建日期" align="center" prop="createTime" :show-overflow-tooltip="true" min-width="20%"/>
	  <el-table-column label="操作" min-width="20%">
			<template slot-scope="scope">
				<el-button size="mini" @click="editHandler(scope.row)">编辑</el-button>
				<el-button size="mini" type="danger" @click="delHandler(scope.row)">删除</el-button>
			</template>
	  </el-table-column>
    </el-table>
		<el-pagination class="pager" layout="total, prev, pager, next, jumper" align="center"
		:total="config.total" :page-sizes="[10,20,100]" :current-page.sync="config.page" 
		@current-change="getList()" :page-size="config.size"></el-pagination>
	
</div>
</template>
<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "/api/info";
import { listKind } from "/api/kind";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { handleTree } from '/utils/listUtils.js'
export default {
  name: 'Info',
  components: { Treeselect },
  data () {
    return {
	  operateType: 'add',
	  isShow: false,
	  operateForm:{
	  	infoTitle: '',
	  	infoContent: '',
		infoKind: '',
	  },
	  loading: true,
      showSearch: true,
	  queryParams: {
	    pageNum: 1,
	    pageSize: 10,
	    dictName: undefined,
	    dictType: undefined,
	  },
	  config: {
	  	page: 1,
	  	size: 10,
	  	total: 30
	  },
	  typeList: [],
	  // 表单校验
	  rules: {
	    dictName: [
	      { required: true, message: "字典名称不能为空", trigger: "blur" },
	    ],
	    dictType: [
	      { required: true, message: "字典类型不能为空", trigger: "blur" },
	    ],
	  },
	  imageUrl: '',
	  imageFilename: '',
	  imgUpload: {
	      // 设置上传的请求头部
	      headers: {
	        Authorization: "Bearer " + localStorage.getItem('token')
	      },
	  },
		kindOptions: [],
		
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询字典类型列表 */
    getList(infoTitle='') {
      this.loading = true;
      listInfo({
				pageNum: this.config.page,
				pageSize: this.config.size,
				infoTitle
		}).then(res => {
			let data = res.data
          this.typeList = data.rows;
          this.config.total = data.total
          this.loading = false;
        }
      );
    },
	/** 下拉树结构 */
	getTreeselect() {
	  listKind().then(response => {
	    this.kindOptions = [];
	    const kind = { id: 0, kindName: '主类目', children: [] };
	    kind.children = handleTree(response.data.data, "id", "pid");
	    this.kindOptions.push(kind);
	  });
	},
	/** 转换菜单数据结构 */
	normalizer(node) {
	  if (node.children && !node.children.length) {
	    delete node.children;
	  }
	  return {
	    id: node.id,
	    label: node.kindName,
	    children: node.children
	  };
	},
	confirm(){
		this.$refs["form"].validate(valid=>{
			if (valid){
				if(this.operateType === 'edit'){
					updateInfo(this.operateForm).then(res => {
						this.isShow=false
						this.getList()
					})
				}
				else{
					addInfo(this.operateForm).then(res => {
						this.isShow=false
						this.getList()
					})
				}
			}
		})
	},
	
	handleSelectionChange(selection) {
	  // this.ids = selection.map(item => item.dictId)
	},
	addHandler(){
		this.isShow = true
		this.operateType = 'add'
		this.operateForm = {
			dictName: '',
			dictType: '',
			remark: ''
		}
		this.getTreeselect();
	},
	editHandler(row){
		this.operateType = 'edit'
		this.isShow = true
		const id = row.id || this.ids
		getInfo(id).then(response => {
		  this.operateForm = response.data.data;
		  this.open = true;
		  this.title = "修改";
		  this.getTreeselect();
		});
	},
	handleQuery() {
	  this.queryParams.pageNum = 1;
	  this.getList();
	},
	delHandler(row){
		this.$confirm("此操作将永久删除该字典，是否继续？", "提示",{
			confirmButtonText: "确认",
			cancelButtonText: "取消",
			type: "warning"
		}).then(()=>{
			const id = row.id
			delInfo(id).then(() => {
				this.$message({
					type: 'success',
					message: '删除成功'
				})
				this.getList()
			})
		})
	},
	clickMenu(item){
		let tar = {name:'dictdata',label:'字典数据'}
		  this.$router.push({
			  name: tar.name,
			  path: '/dictdata/index',
			  params: {dictType: item.dictType}
		  })
		  this.$store.commit('selectMenu', tar)
	},
	
	handleAvatarSuccess(res, file) {
	  this.imageUrl = URL.createObjectURL(file.raw);
	  this.imageFilename =file.response.goodsImg;
	},
	beforeAvatarUpload(file) {
	  const isJPG = file.type === 'image/jpeg' || file.type === "image/png";
	  const isLt2M = file.size / 1024 / 1024 < 2;
	
	  if (!isJPG) {
			  this.$message.warning('上传头像图片只能是 JPG/PNG 格式!')
	  }
	  if (!isLt2M) {
			  this.$message.warning('上传头像图片大小不能超过 2MB!')
	  }
	  return isJPG && isLt2M;
	}
	
  }
}
</script>

<style>
	.avatar-uploader .el-upload {
	  border: 1px dashed #d9d9d9;
	  border-radius: 6px;
	  cursor: pointer;
	  position: relative;
	  overflow: hidden;
	}
	.avatar-uploader .el-upload:hover {
	  border-color: #409EFF;
	}
	.avatar-uploader-icon {
	  font-size: 28px;
	  color: #8c939d;
	  width: 178px;
	  height: 178px;
	  line-height: 178px;
	  text-align: center;
	}
	.avatar {
	  width: 178px;
	  height: 178px;
	  display: block;
	}
</style>